package com.yuantu.judiciary.serviceimpl;

import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.yuantu.judiciary.constant.Regulation;
import com.yuantu.judiciary.dao.*;
import com.yuantu.judiciary.exception.enums.AccountExceptionEnum;
import com.yuantu.judiciary.exception.enums.CheckPersonExceptionEnum;
import com.yuantu.judiciary.exception.enums.OrganizationExceptionEnum;
import com.yuantu.judiciary.model.api.BaseApiResponseMsg;
import com.yuantu.judiciary.model.api.EnterpriseListDTO;
import com.yuantu.judiciary.model.api.SanctionByIdDTO;
import com.yuantu.judiciary.model.api.SanctionByNameDTO;
import com.yuantu.judiciary.model.domain.*;
import com.yuantu.judiciary.model.dto.*;
import com.yuantu.judiciary.model.enums.*;
import com.yuantu.judiciary.model.form.*;
import com.yuantu.judiciary.model.vo.*;
import com.yuantu.judiciary.service.*;
import com.yuantu.judiciary.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * 企业尽调接口实现
 *
 * @author syw
 * @since 2023-07-13
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class CheckEnterpriseServiceImpl implements ICheckEnterpriseService {

    private static final Gson GSON = new Gson();
    private final IOpenApiService openApiService;
    private final ISysFileService fileService;
    private final IQueryRecordDao queryRecordDao;
    private final ISysFileDao fileDao;
    private final IQueryResultDao queryResultDao;
    private final IQueryEntityDao queryEntityDao;
    private final IUserRelationDao userRelationDao;
    private final IUserFollowDao userFollowDao;
    private final IAccountDao accountDao;
    private final IOrganizationDao organizationDao;
    @Value("${upload.file.auth}")
    private String uploadAuthorizedPath;
    private final ISysConfigService sysConfigService;
    private final ICheckResultService checkResultService;
    private final IAgentService agentService;

    @Override
    public PageVO<EntListVO> getEnterpriseList(String enterpriseName, Pageable pageable) {
        Integer page = pageable.getPageNumber() >= 0 ? pageable.getPageNumber() + 1 : 1;
        Integer size = Math.min(pageable.getPageSize(), 20);

        try {
            BaseApiResponseMsg msg = JSON.parseObject(
                    openApiService.enterpriseListProd(new EnterpriseListDTO(enterpriseName, ApiAuthState.AUTHORIZED.ordinal(), size, page)),
                    BaseApiResponseMsg.class
            );

            JsonArray resultJson = GSON.fromJson(msg.getData().toString(), JsonArray.class);
            return new PageVO<>(msg.getTotal().longValue(), StreamSupport.stream(resultJson.spliterator(), true).map(data -> {
                EntListDTO res = JSON.parseObject(data.toString(), EntListDTO.class);
                return new EntListVO(res.getEnterpriseName(), res.getName(), res.getCreditCode(), res.getAreaCode());
            }).collect(Collectors.toList()));
        } catch (Exception e) {
            List<QueryEntityDO> entity = queryEntityDao.findByTypeAndDeletedFalse(SearchType.ENTERPRISE);
            if (CollectionUtils.isEmpty(entity)) {
                return new PageVO<>(0L, Collections.emptyList());
            }

            List<EntListVO> res = new ArrayList<>();
            entity.forEach(data -> {
                QueryResultDO result = queryResultDao.findFirstByEntityIdAndTypeAndDeletedFalse(data.getId(), QueryType.ENT_BASIC);
                if (!ObjectUtils.isEmpty(result) && StringUtils.isNotBlank(result.getResult())) {
                    String companyInfoStr = FileUtil.getTemplateContent(result.getResult());
                    if (StringUtils.isNotBlank(companyInfoStr)) {
                        ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
                        EntBasicDTO basicInfo = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBASIC).orElse(new EntBasicDTO());

                        EntListVO basic = new EntListVO();
                        basic.setEnterpriseName(basicInfo.getENTNAME());
                        basic.setName(basicInfo.getFRNAME());
                        basic.setCreditCode(basicInfo.getCREDITCODE());
                        basic.setAreaCode(basicInfo.getREGORGCODE());
                        res.add(basic);
                    }
                }
            });
            return new PageVO<>((long) res.size(), PageUtil.getPage(res, pageable));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadAuthorizedFile(Long userId, MultipartFile file, String enterpriseName) {
      //  Boolean configState = sysConfigService.getConfigState(ConfigType.AUTH_ENTER);
        String url;
//        if (Boolean.TRUE.equals(configState)) {
//            // 文件上传
//            url = fileService.fileUpload(file, uploadAuthorizedPath);
//        } else {
//            url = uploadAuthorizedPath + "/" + "without-auth";
//        }
       if(file != null){
           url = fileService.fileUpload(file, uploadAuthorizedPath);
       }else {
           url = uploadAuthorizedPath + "/" + "without-auth";
       }


//        if(!queryRecord.getIsFile()){
//            AssertUtil.assertTrue(!AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.AUTHORIZED_PASS_NOT_SEND_REPEAT);
//        }
        return url;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long uploadAuthorizedFileByAli(Long userId, MultipartFile file, String enterpriseName) {
        String url = fileService.fileUpload(file, uploadAuthorizedPath);

        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(enterpriseName, "", "");
        String content = JSON.toJSONString(searchRecord);
        QueryRecordDO queryRecord = new QueryRecordDO();
        queryRecord.setCreatorId(userId);
        queryRecord.setContent(content);
        queryRecord.setType(SearchType.ENTERPRISE);
        QueryEntityDO entity = queryEntityDao.findByNameAndCodeAndTypeAndCreatorIdAndDeletedFalse(searchRecord.getName(), "", SearchType.ENTERPRISE, userId);
        if (ObjectUtils.isEmpty(entity)) {
            entity = new QueryEntityDO(searchRecord.getName(), "", SearchType.ENTERPRISE);
            entity.setCreatorId(userId);
            queryEntityDao.save(entity);
        }
        queryRecord.setEntityId(entity.getId());
        queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
        queryRecord.setAuthorizedTime(new Timestamp(System.currentTimeMillis()));
        queryRecord.setOrigin(EndpointType.ALIPAY_APPLET);
        queryRecord.setShow(false);
        queryRecordDao.save(queryRecord);

        // 添加授权文件
        SysFileDO sysFile = new SysFileDO();
        sysFile.setUrl(url);
        sysFile.setRelativeId(queryRecord.getId());
        sysFile.setRelativeType(FileRelativeType.ENT_AUTH);
        fileDao.save(sysFile);
        return queryRecord.getId();
    }

    @Override
    public Long addAuthorizedRecord(Long userId, AddEntAuthRecordForm form) {
        // 默认授权通过
//        QueryRecordDO queryRecord = queryRecordDao.findByCreatorIdAndTypeAndContentAndDeletedFalse(
//                userId, SearchType.ENTERPRISE, JSON.toJSONString(new SearchRecordContentDTO(form.getName(), "", "")));
//        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(form.getName(), "", "");
        String content = JSON.toJSONString(searchRecord);
        //QueryRecordDO queryRecord = queryRecordDao.findByCreatorIdAndTypeAndContentAndDeletedFalse(userId, SearchType.ENTERPRISE, content);
        //if (ObjectUtils.isEmpty(queryRecord)) {
        QueryRecordDO queryRecord = new QueryRecordDO();
        queryRecord.setCreatorId(userId);
        queryRecord.setContent(content);
        queryRecord.setType(SearchType.ENTERPRISE);
        queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
        //} else {
        queryRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        //}

        QueryEntityDO entity;
        if (ObjectUtils.isEmpty(queryRecord.getEntityId())) {
            entity = queryEntityDao.findByNameAndCodeAndTypeAndCreatorIdAndDeletedFalse(searchRecord.getName(), "", SearchType.ENTERPRISE, userId);
        } else {
            entity = queryEntityDao.findByIdAndDeletedFalse(queryRecord.getEntityId());
        }
        if (ObjectUtils.isEmpty(entity)) {
            entity = new QueryEntityDO(searchRecord.getName(), "", SearchType.ENTERPRISE);
            entity.setCreatorId(userId);
            queryEntityDao.save(entity);
        }
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
        }
        //当前应该消耗的套餐类型，当前平台为Applet
        EndpointType endpointType = agentService.currentUseSearchTimeEndpoint(userId, EndpointType.APPLET);
        if(endpointType.equals(EndpointType.H5)){
            String tradeNo = agentService.getOldestOrderTradeNo(userId);
            queryRecord.setTradeNo(tradeNo);
        }
        queryRecordDao.save(queryRecord);
        queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
        queryRecord.setAuthorizedTime(new Timestamp(System.currentTimeMillis()));
        queryRecord.setCodeInfo(form.getCodeInfo());
        queryRecordDao.save(queryRecord);

        // 添加授权文件
        SysFileDO file = new SysFileDO();
        file.setName(form.getFileName());
        file.setUrl(form.getFileUrl());
        file.setType(form.getFileType());
        file.setSize(form.getFileSize());
        file.setRelativeId(queryRecord.getId());
        file.setRelativeType(FileRelativeType.ENT_AUTH);
        fileDao.save(file);
        return queryRecord.getId();
    }

    @Override
    public CheckEnterpriseBriefVO getBrief(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseBriefVO res = new CheckEnterpriseBriefVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);

        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);

        res.setId(queryRecord.getId());
        UserFollowDO follow = userFollowDao.findByEntityIdAndCreatorIdAndDeletedFalse(queryRecord.getEntityId(), userId);
        res.setIsFollow(!ObjectUtils.isEmpty(follow));

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
            EntBasicDTO basic = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBASIC).orElse(new EntBasicDTO());
            res.setEnterpriseName(basic.getENTNAME());
            res.setOldName(basic.getENTNAME_OLD());
            res.setType(basic.getENTTYPE());
            res.setStatus(basic.getENTSTATUS());
            res.setName(basic.getFRNAME());
            res.setEsDate(basic.getESDATE());
            res.setRegCap(basic.getREGCAP());
        }

        return res;
    }

    @Override
    public List<UserRelationVO> getRelationAtlas(Long userId, UserRelationType type) {
        AccountDO account = accountDao.findByIdAndDeletedFalse(userId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        List<UserRelationDO> userRelation = userRelationDao.findByCreatorIdAndTypeAndDeletedFalse(userId, type);

        List<UserRelationVO> res = new ArrayList<>();
        if (ObjectUtils.isEmpty(account.getOrganizationId())) {
            res.add(new UserRelationVO(0L, account.getUsername()));
        } else {
            OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
            AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);
            String company = OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
            res.add(new UserRelationVO(0L, company));
        }

        if (CollectionUtils.isEmpty(userRelation)) {
            return res;
        }

        List<Long> entityIds = userRelation.stream()
                .filter(Objects::nonNull)
                .map(UserRelationDO::getEntityId).distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(entityIds)) {
            return res;
        }

        Map<Long, String> entityMap = queryEntityDao.findByIdInAndDeletedFalse(entityIds).stream()
                .collect(Collectors.toMap(QueryEntityDO::getId, QueryEntityDO::getName));
        Map<Long, Long> queryMap = queryRecordDao.findByCreatorIdAndEntityIdInAndDeletedFalse(userId, entityIds).stream()
                .collect(Collectors.toMap(QueryRecordDO::getEntityId, QueryRecordDO::getId));
        res.addAll(userRelation.stream().map(data ->
                new UserRelationVO(queryMap.get(data.getEntityId()), entityMap.get(data.getEntityId()))
        ).collect(Collectors.toList()));
        return res;
    }

    @Override
    public CheckEnterpriseReportVO getReport(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);
        AccountDO account = accountDao.findByIdAndDeletedFalse(userId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        CheckEnterpriseReportVO res = new CheckEnterpriseReportVO();
        EntReportBasicDTO basic = new EntReportBasicDTO();
        EntReportCaseNumDTO caseNum = new EntReportCaseNumDTO();
        EntReportLitigationStatusDTO litigationStatus = new EntReportLitigationStatusDTO();
        PortraitDebtVO debt = new PortraitDebtVO();

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);

        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
            EntBasicDTO basicInfo = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBASIC).orElse(new EntBasicDTO());

            String company = OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
            basic.setCreatorName(company);
            basic.setUserName(account.getUsername());
            basic.setName(basicInfo.getENTNAME());
            basic.setFrName(basicInfo.getFRNAME());
            basic.setEsDate(basicInfo.getESDATE());
            basic.setRegCap(basicInfo.getREGCAP());
        }

        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> data = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = data.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            int total = 0;
            Map<String, Integer> map = new HashMap<>();
            map.put("active", 0);
            map.put("passive", 0);
            Map<String, Double> activeMap = new HashMap<>();
            Map<String, Double> passiveMap = new HashMap<>();
            Map<String, Integer> caseNumMap = new HashMap<>();

            for (CaseCategory category : CaseCategory.getCaseCategory()) {
                List<CaseDataDTO> cases = detailMap.get(category.getCode());
                caseNumMap.put(category.getCode(), cases.size());
                total = total + cases.size();
                if (!CollectionUtils.isEmpty(cases)) {
                    judgeLitigationStatus(category, map, cases);
                    countDebtAmount(category, cases, activeMap, passiveMap, null, null);
                }
            }
            caseNum.setJurisdiction(caseNumMap.get(CaseCategory.JURISDICTION.getCode()));
            caseNum.setPreservation(caseNumMap.get(CaseCategory.PRESERVATION.getCode()));
            caseNum.setAdministrative(caseNumMap.get(CaseCategory.ADMINISTRATIVE.getCode()));
            caseNum.setCivil(caseNumMap.get(CaseCategory.CIVIL.getCode()));
            caseNum.setImplement(caseNumMap.get(CaseCategory.IMPLEMENT.getCode()));
            caseNum.setBankrupt(caseNumMap.get(CaseCategory.BANKRUPT.getCode()));
            caseNum.setCompensate(caseNumMap.get(CaseCategory.COMPENSATE.getCode()));
            caseNum.setCriminal(caseNumMap.get(CaseCategory.CRIMINAL.getCode()));

            litigationStatus.setActive(map.get("active"));
            litigationStatus.setPassive(map.get("passive"));
            litigationStatus.setOther(total - map.get("active") - map.get("passive"));

            debt.setClaimAmount(DoubleUtil.transferAmount(activeMap.values().stream().mapToDouble(Double::doubleValue).sum()));
            debt.setLiabilityAmount(DoubleUtil.transferAmount(passiveMap.values().stream().mapToDouble(Double::doubleValue).sum()));
            buildDebtData(activeMap, passiveMap, debt);
        }

        res.setBasic(basic);
        res.setCaseNum(caseNum);
        res.setLitigationStatus(litigationStatus);
        res.setDebt(debt);
        return res;
    }

    @Override
    public List<UserRelationVO> getAllRelationAtlas(Long userId) {
        List<UserRelationDO> userRelation = userRelationDao.findByCreatorIdAndDeletedFalse(userId);

        List<UserRelationVO> res = new ArrayList<>();
        AccountDO account = accountDao.findByIdAndDeletedFalse(userId);
        String name;
        if (ObjectUtils.isEmpty(account) || ObjectUtils.isEmpty(account.getOrganizationId())) {
            name = account.getUsername();
        } else {
            OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
            if (ObjectUtils.isEmpty(organization)) {
                log.info("账号: {} 绑定组织 {} 不存在", account.getId(), account.getOrganizationId());
                AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), AccountExceptionEnum.REGISTER_APPLYING);
            }
            if (OrganizationType.SINGLE.equals(organization.getType())) {
                name = organization.getUsername();
            } else {
                name = organization.getEnterName();
            }
        }
        res.add(new UserRelationVO(null, name));
        if (CollectionUtils.isEmpty(userRelation)) {
            return res;
        }

        List<Long> entityIds = userRelation.stream()
                .filter(Objects::nonNull)
                .map(UserRelationDO::getEntityId).distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(entityIds)) {
            return res;
        }

        Map<Long, String> entityMap = queryEntityDao.findByIdInAndDeletedFalse(entityIds).stream()
                .collect(Collectors.toMap(QueryEntityDO::getId, QueryEntityDO::getName));
        Map<Long, Long> queryMap = queryRecordDao.findByCreatorIdAndEntityIdInAndDeletedFalse(userId, entityIds).stream()
                .collect(Collectors.toMap(QueryRecordDO::getEntityId, QueryRecordDO::getId));

        List<UserRelationVO> customer = userRelation.stream()
                .filter(f -> UserRelationType.CUSTOMER.equals(f.getType()))
                .map(data ->
                        new UserRelationVO(queryMap.get(data.getEntityId()), entityMap.get(data.getEntityId()))
                ).collect(Collectors.toList());
        List<UserRelationVO> supplier = userRelation.stream()
                .filter(f -> UserRelationType.SUPPLIER.equals(f.getType()))
                .map(data ->
                        new UserRelationVO(queryMap.get(data.getEntityId()), entityMap.get(data.getEntityId()))
                ).collect(Collectors.toList());
        res.get(0).setChildren(new ArrayList<>());
        res.get(0).getChildren().add(new UserRelationVO("客户", customer));
        res.get(0).getChildren().add(new UserRelationVO("供应商", supplier));
        return res;
    }

    @Override
    public PortraitDebtVO getPortraitByDebt(Long userId, GetPortraitInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        PortraitDebtVO res = new PortraitDebtVO();

        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> data = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = data.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            Map<String, Double> activeMap = new HashMap<>();
            Map<String, Double> passiveMap = new HashMap<>();

            for (CaseCategory category : CaseCategory.getCaseCategory()) {
                List<CaseDataDTO> cases = detailMap.get(category.getCode());
                countDebtAmount(category, cases, activeMap, passiveMap, form.getStartTime(), form.getEndTime());
            }

            res.setClaimAmount(DoubleUtil.transferAmount(activeMap.values().stream().mapToDouble(Double::doubleValue).sum()));
            res.setLiabilityAmount(DoubleUtil.transferAmount(passiveMap.values().stream().mapToDouble(Double::doubleValue).sum()));
            buildDebtData(activeMap, passiveMap, res);
        }

        return res;
    }

    @Override
    public PortraitTrendVO getPortraitByTrend(Long userId, GetPortraitTrendForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        PortraitTrendVO res = new PortraitTrendVO();
        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            Map<String, Integer> caseNumMap = new HashMap<>();
            Map<String, Integer> caseReasonMap = new HashMap<>();

            List<CaseCategory> caseCategory = Arrays.asList(CaseCategory.CIVIL, CaseCategory.CRIMINAL, CaseCategory.ADMINISTRATIVE, CaseCategory.IMPLEMENT);
            if (CaseCategory.ALL.equals(form.getCaseCategory())) {
                for (CaseCategory category : caseCategory) {
                    List<CaseDataDTO> cases = detailMap.get(category.getCode());
                    countCaseNumByCategory(form, caseNumMap, caseReasonMap, cases);
                }
            } else if (caseCategory.contains(form.getCaseCategory())) {
                List<CaseDataDTO> cases = detailMap.get(form.getCaseCategory().getCode());
                countCaseNumByCategory(form, caseNumMap, caseReasonMap, cases);
            }

            if (!CollectionUtils.isEmpty(caseNumMap)) {
                Map<Date, Integer> caseNumData = caseNumMap.entrySet().stream().collect(Collectors.groupingBy(item ->
                        TimeUtil.transferTimeDate(item.getKey(), Regulation.YEAR_MONTH), Collectors.summingInt(Map.Entry::getValue)));
                Date minDate = new Date(caseNumData.keySet().stream().mapToLong(Date::getTime).min().getAsLong());
                Date maxDate = new Date(caseNumData.keySet().stream().mapToLong(Date::getTime).max().getAsLong());

                List<String> xAxis = TimeUtil.getMonthBetween(minDate, maxDate, Regulation.YEAR_MONTH, Calendar.MONTH);
                res.setXAxis(xAxis.stream().map(d -> d.replace("-", ".")).collect(Collectors.toList()));
                List<Integer> yAxis = xAxis.stream().map(data -> caseNumData.getOrDefault(TimeUtil.transferTimeDate(data, Regulation.YEAR_MONTH), 0)).collect(Collectors.toList());
                res.setYAxis(yAxis);
            }

            if (!CollectionUtils.isEmpty(caseReasonMap)) {
                List<CaseReasonNumDTO> caseReasons = caseReasonMap.entrySet().stream().map(m ->
                        new CaseReasonNumDTO(m.getKey(), m.getValue())
                ).sorted(Comparator.comparing(CaseReasonNumDTO::getNum).reversed()).limit(4).collect(Collectors.toList());
                res.setCaseReasons(caseReasons);
            }
        }
        return res;
    }

    @Override
    public PortraitAnalyzeVO getPortraitByAnalyze(Long userId, GetPortraitTrendForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        PortraitAnalyzeVO res = new PortraitAnalyzeVO();
        Map<String, Integer> map = new HashMap<>();
        map.put("total", 0);
        map.put("active", 0);
        map.put("passive", 0);
        map.put("firstTrial", 0);
        map.put("secondTrial", 0);
        map.put("thirdTrial", 0);

        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            List<CaseCategory> caseCategory = Arrays.asList(CaseCategory.CIVIL, CaseCategory.CRIMINAL, CaseCategory.ADMINISTRATIVE, CaseCategory.IMPLEMENT);

            if (CaseCategory.ALL.equals(form.getCaseCategory())) {
                for (CaseCategory category : caseCategory) {
                    List<CaseDataDTO> cases = detailMap.get(category.getCode());
                    if (!CollectionUtils.isEmpty(cases)) {
                        countLitigationStatus(category, map, cases, form.getStartTime(), form.getEndTime());
                    }
                }
            } else if (caseCategory.contains(form.getCaseCategory())) {
                List<CaseDataDTO> cases = detailMap.get(form.getCaseCategory().getCode());
                if (!CollectionUtils.isEmpty(cases)) {
                    countLitigationStatus(form.getCaseCategory(), map, cases, form.getStartTime(), form.getEndTime());
                }
            }
        }

        res.setFirstTrial(map.get("firstTrial"));
        res.setSecondTrial(map.get("secondTrial"));
        res.setThirdTrial(map.get("thirdTrial"));
        res.setActiveNum(map.get("active"));
        res.setPassiveNum(map.get("passive"));
        res.setOtherNum(map.get("total") - map.get("active") - map.get("passive"));
        return res;
    }

    @Override
    public PortraitAmountVO getPortraitByAmount(Long userId, GetPortraitAmountForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        PortraitAmountVO res = new PortraitAmountVO();
        Map<String, Double> map = new HashMap<>();
        map.put("activeNum", 0.0);
        map.put("passiveNum", 0.0);
        map.put("activeExecuteNum", 0.0);
        map.put("passiveExecuteNum", 0.0);
        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            List<CaseCategory> caseCategory = Arrays.asList(CaseCategory.CIVIL, CaseCategory.CRIMINAL,
                    CaseCategory.ADMINISTRATIVE, CaseCategory.IMPLEMENT, CaseCategory.PRESERVATION);
            for (CaseCategory category : caseCategory) {
                List<CaseDataDTO> cases = detailMap.get(category.getCode());
                if (!CollectionUtils.isEmpty(cases)) {
                    countLitigationStatusAmount(category, map, cases, form);
                }
            }
        }

        res.setActiveNum(DoubleUtil.transferAmount(map.get("activeNum")));
        res.setPassiveNum(DoubleUtil.transferAmount(map.get("passiveNum")));
        res.setActiveExecuteNum(DoubleUtil.transferAmount(map.get("activeExecuteNum")));
        res.setPassiveExecuteNum(DoubleUtil.transferAmount(map.get("passiveExecuteNum")));
        return res;
    }

    private void countLitigationStatusAmount(CaseCategory category, Map<String, Double> countMap, List<CaseDataDTO> cases, GetPortraitAmountForm form) {
        double activeNum = countMap.get("activeNum");
        double passiveNum = countMap.get("passiveNum");
        double activeExecuteNum = countMap.get("activeExecuteNum");
        double passiveExecuteNum = countMap.get("passiveExecuteNum");

        if (CaseCategory.PRESERVATION.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(form.getStartTime(), form.getEndTime(), data.getD_larq()) || verifyCaseState(form.getCaseState(), data)) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "非诉财产保全审查".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "申请人".equals(data.getN_ssdw())) {
                        activeNum = activeNum + (StringUtils.isBlank(data.getN_sqbqse()) ? 0.0 : Double.parseDouble(data.getN_sqbqse()));
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被申请人".equals(data.getN_ssdw())) {
                        passiveNum = passiveNum + (StringUtils.isBlank(data.getN_sqbqse()) ? 0.0 : Double.parseDouble(data.getN_sqbqse()));
                    }
                }
            }
        } else if (CaseCategory.ADMINISTRATIVE.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(form.getStartTime(), form.getEndTime(), data.getD_larq()) || verifyCaseState(form.getCaseState(), data)) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "原告".equals(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被告".equals(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告").contains(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告").contains(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    }
                }
            }
        } else if (CaseCategory.CIVIL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(form.getStartTime(), form.getEndTime(), data.getD_larq()) || verifyCaseState(form.getCaseState(), data)) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原告", "反诉原告").contains(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告", "反诉被告").contains(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (!ObjectUtils.isEmpty(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告", "原审申请人").contains(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告", "原审被申请人").contains(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_qsbdje());
                    }
                }
            }
        } else if (CaseCategory.IMPLEMENT.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(form.getStartTime(), form.getEndTime(), data.getD_larq()) || verifyCaseState(form.getCaseState(), data)) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("申请执行人", "申请复议人", "申请人").contains(data.getN_ssdw())) {
                    activeExecuteNum = countCaseNum(activeExecuteNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_sqzxbdje());
                } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被执行人", "被申请人").contains(data.getN_ssdw())) {
                    passiveExecuteNum = countCaseNum(passiveExecuteNum, data.getN_ajjzjd(), data.getN_jabdje(), data.getN_sqzxbdje());
                }
            }
        } else if (CaseCategory.CRIMINAL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(form.getStartTime(), form.getEndTime(), data.getD_larq()) || verifyCaseState(form.getCaseState(), data)) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("自诉人", "反诉人", "附带民事诉讼原告", "附带民事诉讼反诉原告").contains(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_pcpcje(), data.getN_bqqpcje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告人", "反诉被告人", "附带民事诉讼被告", "附带民事诉讼反诉被告").contains(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_pcpcje(), data.getN_bqqpcje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审附带民事诉讼原告", "申请复议人", "原审反诉人").contains(data.getN_ssdw())) {
                        activeNum = countCaseNum(activeNum, data.getN_ajjzjd(), data.getN_pcpcje(), data.getN_bqqpcje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原审被告人", "原审附带民事诉讼被告", "原审被申请人", "犯罪嫌疑人", "原审反诉被告人").contains(data.getN_ssdw())) {
                        passiveNum = countCaseNum(passiveNum, data.getN_ajjzjd(), data.getN_pcpcje(), data.getN_bqqpcje());
                    }
                }
            }
        }

        countMap.put("activeNum", activeNum);
        countMap.put("passiveNum", passiveNum);
        countMap.put("activeExecuteNum", activeExecuteNum);
        countMap.put("passiveExecuteNum", passiveExecuteNum);
    }

    private double countCaseNum(double num, String condition, String closedCaseAmount, String notClosedCaseAmount) {
        if ("已结案".equals(condition)) {
            num = num + (StringUtils.isBlank(closedCaseAmount) ? 0.0 : Double.parseDouble(closedCaseAmount));
        } else if ("未结案".equals(condition)) {
            num = num + (StringUtils.isBlank(notClosedCaseAmount) ? 0.0 : Double.parseDouble(notClosedCaseAmount));
        }
        return num;
    }

    private boolean verifyCaseState(CaseState caseState, CaseDataDTO data) {
        return !ObjectUtils.isEmpty(caseState) && !CaseState.ALL.equals(caseState) && (StringUtils.isBlank(data.getN_ajjzjd()) || !caseState.getValue().equals(data.getN_ajjzjd()));
    }

    @Override
    public List<PortraitRelationVO> getPortraitByRelation(Long userId, GetPortraitInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        Map<String, Integer> countMap = new HashMap<>();
        List<String> relativeName = new ArrayList<>();
        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataDTO> resJudicialData = JSON.parseArray(judicialStr, ResJudicialDataDTO.class);
            ResJudicialDataDTO judicialResult = resJudicialData.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            for (String category : CaseCategory.getCaseCategoryCode()) {
                List<CaseDataDTO> cases = detailMap.get(category);
                if (!CollectionUtils.isEmpty(cases)) {
                    countCase(countMap, relativeName, cases, form.getStartTime(), form.getEndTime());
                }
            }
        }
        List<PortraitRelationVO> res = countMap.entrySet().stream().filter(f -> !searchRecord.getName().equals(f.getKey()))
                .map(data -> new PortraitRelationVO(data.getKey(), data.getValue())).sorted(Comparator.comparing(PortraitRelationVO::getNumber).reversed())
                .collect(Collectors.toList());
        res.addAll(relativeName.stream().map(name -> new PortraitRelationVO(name, 1)).collect(Collectors.toList()));
        if(res.size() > 200){
            res = res.subList(0, 200);
        }
        return res;
    }

    private void countCase(Map<String, Integer> countMap, List<String> relativeName, List<CaseDataDTO> cases, Timestamp startTime, Timestamp endTime) {
        for (CaseDataDTO data : cases) {
            if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                continue;
            }
            if (!CollectionUtils.isEmpty(data.getC_dsrxx())) {
                data.getC_dsrxx().forEach(item -> {
                    if (!ObjectUtils.isEmpty(item.getN_dsrlx()) && "企业组织".equals(item.getN_dsrlx()) && !ObjectUtils.isEmpty(item.getC_mc())) {
                        countCaseNum(item.getC_mc(), countMap);
                    }
                    if (!ObjectUtils.isEmpty(item.getN_dsrlx()) && "自然人".equals(item.getN_dsrlx()) && !ObjectUtils.isEmpty(item.getC_mc())) {
                        relativeName.add(item.getC_mc());
                    }
                });
            }
        }
    }

    @Override
    public PortraitAreaVO getPortraitByArea(Long userId, GetPortraitInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String judicialStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        PortraitAreaVO res = new PortraitAreaVO();
        List<String> xAxis = new ArrayList<>();
        List<Integer> yAxis = new ArrayList<>();
        Map<String, Integer> countMap = new HashMap<>();
        if (StringUtils.isNotBlank(judicialStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            Map<String, List<CaseDataDTO>> detailMap = judicialResult.getCaseData();

            for (String category : CaseCategory.getCaseCategoryCode()) {
                List<CaseDataDTO> cases = detailMap.get(category);
                if (!CollectionUtils.isEmpty(cases)) {
                    countAreaCaseNum(countMap, cases, form.getStartTime(), form.getEndTime());
                }
            }

            if (!CollectionUtils.isEmpty(countMap)) {
                countMap.forEach((key, value) -> {
                    xAxis.add(key);
                    yAxis.add(value);
                });
            }
        }

        res.setXAxis(xAxis);
        res.setYAxis(yAxis);
        return res;
    }

    @Override
    public PageVO<SanctionVO> getSanctionList(String enterpriseName, Pageable pageable) {
        if (StringUtils.isBlank(enterpriseName)) {
            return new PageVO<>(0L, Collections.emptyList());
        }

        Integer page = pageable.getPageNumber() >= 0 ? pageable.getPageNumber() + 1 : 1;
        Integer size = Math.min(pageable.getPageSize(), 20);

        try {
            String msg = openApiService.sanctionList(new SanctionByNameDTO(enterpriseName, ApiAuthState.AUTHORIZED.ordinal(), size, page));
            ResSanctionListDTO data = JSON.parseObject(msg, ResSanctionListDTO.class);
            long total = ObjectUtils.isEmpty(data.getTotal()) ? 0L : data.getTotal();
            List<SanctionVO> pageList = CollectionUtils.isEmpty(data.getItems()) ? Collections.emptyList() : data.getItems();
            return new PageVO<>(total, pageList);
        } catch (Exception e) {
            log.error("获取制裁列表错误：" + e.getMessage(), e);
            return new PageVO<>(0L, Collections.emptyList());
        }
    }

    @Override
    public SanctionInfoVO getSanctionById(GetSanctionInfoForm form) {
        try {
            String msg = openApiService.sanctionById(new SanctionByIdDTO(form.getId(), ApiAuthState.AUTHORIZED.ordinal()));
            List<SanctionInfoVO> data = JSON.parseArray(msg, SanctionInfoVO.class);
            return data.get(0);
        } catch (Exception e) {
            log.error("获取制裁信息错误：" + e.getMessage(), e);
            return new SanctionInfoVO();
        }
    }

    @Override
    public Long entAuthQueryRecord(Long userId, String name, String codeInfo) {

        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(name, "", "");
        String content = JSON.toJSONString(searchRecord);
        QueryRecordDO queryRecord = queryRecordDao.findByCreatorIdAndTypeAndContentAndDeletedFalse(userId, SearchType.ENTERPRISE, content);
        if (ObjectUtils.isEmpty(queryRecord)) {
            queryRecord = new QueryRecordDO();
            queryRecord.setCreatorId(userId);
            queryRecord.setContent(content);
            queryRecord.setCodeInfo(codeInfo);
            queryRecord.setType(SearchType.ENTERPRISE);
        } else {
            Timestamp now = new Timestamp(System.currentTimeMillis());
            queryRecord.setLatestDataTime(now);
            queryRecord.setCreateTime(now);
        }
        queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
        QueryEntityDO entity;
        if (ObjectUtils.isEmpty(queryRecord.getEntityId())) {
            entity = queryEntityDao.findByNameAndCodeAndTypeAndCreatorIdAndDeletedFalse(searchRecord.getName(), "", SearchType.ENTERPRISE, userId);
        } else {
            entity = queryEntityDao.findByIdAndDeletedFalse(queryRecord.getEntityId());
        }
        if (ObjectUtils.isEmpty(entity)) {
            entity = new QueryEntityDO(searchRecord.getName(), "", SearchType.ENTERPRISE);
            entity.setCreatorId(userId);
            queryEntityDao.save(entity);
        }
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
        }
        queryRecordDao.save(queryRecord);
        return queryRecord.getId();
    }

    public void countAreaCaseNum(
            Map<String, Integer> countMap, List<CaseDataDTO> cases, Timestamp startTime, Timestamp endTime
    ) {
        for (CaseDataDTO data : cases) {
            if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                continue;
            }
            if (StringUtils.isNotBlank(data.getC_ssdy())) {
                countCaseNum(data.getC_ssdy(), countMap);
            }
        }
    }

    private void countLitigationStatus(
            CaseCategory category, Map<String, Integer> countMap, List<CaseDataDTO> cases,
            Timestamp startTime, Timestamp endTime
    ) {
        int total = countMap.get("total");
        int active = countMap.get("active");
        int passive = countMap.get("passive");
        int firstTrial = countMap.get("firstTrial");
        int secondTrial = countMap.get("secondTrial");
        int thirdTrial = countMap.get("thirdTrial");

        if (CaseCategory.ADMINISTRATIVE.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                    continue;
                }
                total = total + 1;
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    firstTrial = firstTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "原告".equals(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被告".equals(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    secondTrial = secondTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告").contains(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告").contains(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && Arrays.asList("再审", "再审审查").contains(data.getN_slcx())) {
                    thirdTrial = thirdTrial + 1;
                }
            }
        } else if (CaseCategory.CIVIL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                    continue;
                }
                total = total + 1;
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    firstTrial = firstTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原告", "反诉原告").contains(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告", "反诉被告").contains(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    secondTrial = secondTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告", "原审申请人").contains(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告", "原审被申请人").contains(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && Arrays.asList("再审", "再审审查").contains(data.getN_slcx())) {
                    thirdTrial = thirdTrial + 1;
                }
            }
        } else if (CaseCategory.IMPLEMENT.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                    continue;
                }
                total = total + 1;
                if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("申请执行人", "申请复议人", "申请人").contains(data.getN_ssdw())) {
                    active = active + 1;
                } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被执行人", "被申请人").contains(data.getN_ssdw())) {
                    passive = passive + 1;
                }
            }
        } else if (CaseCategory.CRIMINAL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isBlank(data.getD_larq()) || verifySearchTime(startTime, endTime, data.getD_larq())) {
                    continue;
                }
                total = total + 1;
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    firstTrial = firstTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("自诉人", "反诉人", "附带民事诉讼原告", "附带民事诉讼反诉原告").contains(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告人", "反诉被告人", "附带民事诉讼被告", "附带民事诉讼反诉被告").contains(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    secondTrial = secondTrial + 1;
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审附带民事诉讼原告", "申请复议人", "原审反诉人").contains(data.getN_ssdw())) {
                        active = active + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原审被告人", "原审附带民事诉讼被告", "原审被申请人", "犯罪嫌疑人", "原审反诉被告人").contains(data.getN_ssdw())) {
                        passive = passive + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && Arrays.asList("再审", "再审审查").contains(data.getN_slcx())) {
                    thirdTrial = thirdTrial + 1;
                }
            }
        }

        countMap.put("total", total);
        countMap.put("firstTrial", firstTrial);
        countMap.put("secondTrial", secondTrial);
        countMap.put("thirdTrial", thirdTrial);
        countMap.put("active", active);
        countMap.put("passive", passive);
    }

    public static void countCaseNum(String code, Map<String, Integer> countMap) {
        if (!countMap.containsKey(code)) {
            countMap.put(code, 1);
        } else {
            Integer count = countMap.get(code);
            countMap.put(code, count + 1);
        }
    }

    private void countCaseNumByCategory(GetPortraitTrendForm form, Map<String, Integer> caseNumMap, Map<String, Integer> caseReasonMap, List<CaseDataDTO> civilCases) {
        for (CaseDataDTO data : civilCases) {
            String time = data.getD_larq();
            if (StringUtils.isBlank(time) || verifySearchTime(form.getStartTime(), form.getEndTime(), time)) {
                continue;
            }

            if (caseNumMap.containsKey(time)) {
                Integer count = caseNumMap.get(time);
                caseNumMap.put(time, count + 1);
            } else {
                caseNumMap.put(time, 1);
            }

            if (StringUtils.isNotBlank(data.getN_laay_tree())) {
                String[] reason = data.getN_laay_tree().split(",");
                if (caseReasonMap.containsKey(reason[reason.length - 1])) {
                    Integer count = caseReasonMap.get(reason[reason.length - 1]);
                    caseReasonMap.put(reason[reason.length - 1], count + 1);
                } else {
                    caseReasonMap.put(reason[reason.length - 1], 1);
                }
            }
        }
    }

    private void buildDebtData(Map<String, Double> activeMap, Map<String, Double> passiveMap, PortraitDebtVO debt) {
        if (!CollectionUtils.isEmpty(activeMap) || !CollectionUtils.isEmpty(passiveMap)) {
            Map<Date, Double> activeData = activeMap.entrySet().stream().collect(Collectors.groupingBy(item ->
                    TimeUtil.transferTimeDate(item.getKey(), Regulation.YEAR_MONTH), Collectors.summingDouble(Map.Entry::getValue)));
            Map<Date, Double> passiveData = passiveMap.entrySet().stream().collect(Collectors.groupingBy(item ->
                    TimeUtil.transferTimeDate(item.getKey(), Regulation.YEAR_MONTH), Collectors.summingDouble(Map.Entry::getValue)));
            Date minDate;
            Date maxDate;
            if (CollectionUtils.isEmpty(activeMap)) {
                minDate = new Date(passiveData.keySet().stream().mapToLong(Date::getTime).min().getAsLong());
                maxDate = new Date(passiveData.keySet().stream().mapToLong(Date::getTime).max().getAsLong());
            } else if (CollectionUtils.isEmpty(passiveMap)) {
                minDate = new Date(activeData.keySet().stream().mapToLong(Date::getTime).min().getAsLong());
                maxDate = new Date(activeData.keySet().stream().mapToLong(Date::getTime).max().getAsLong());
            } else {
                minDate = new Date(Math.min(activeData.keySet().stream().mapToLong(Date::getTime).min().getAsLong(),
                        passiveData.keySet().stream().mapToLong(Date::getTime).min().getAsLong()));
                maxDate = new Date(Math.max(activeData.keySet().stream().mapToLong(Date::getTime).max().getAsLong(),
                        passiveData.keySet().stream().mapToLong(Date::getTime).max().getAsLong()));
            }
            List<String> xAxis = TimeUtil.getMonthBetween(minDate, maxDate, Regulation.YEAR_MONTH, Calendar.MONTH);
            debt.setXAxis(xAxis.stream().map(d -> d.replace("-", ".")).collect(Collectors.toList()));
            List<Double> liabilityAxis = xAxis.stream().map(data -> DoubleUtil.transferAmount(passiveData.getOrDefault(TimeUtil.transferTimeDate(data, Regulation.YEAR_MONTH), 0.0))).collect(Collectors.toList());
            debt.setLiabilityAxis(liabilityAxis);
            List<Double> claimAxis = xAxis.stream().map(data -> DoubleUtil.transferAmount(activeData.getOrDefault(TimeUtil.transferTimeDate(data, Regulation.YEAR_MONTH), 0.0))).collect(Collectors.toList());
            debt.setClaimAxis(claimAxis);
        }
    }

    private void countDebtAmount(CaseCategory category, List<CaseDataDTO> cases, Map<String, Double> activeMap, Map<String, Double> passiveMap, Timestamp startTime, Timestamp endTime) {
        if (CaseCategory.PRESERVATION.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (verifyCountAmount(data) || verifySearchTime(startTime, endTime, data.getD_jarq())) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "非诉财产保全审查".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "申请人".equals(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_sqbqse());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被申请人".equals(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_sqbqse());
                    }
                }
            }
        } else if (CaseCategory.ADMINISTRATIVE.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (verifyCountAmount(data) || verifySearchTime(startTime, endTime, data.getD_jarq())) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "原告".equals(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_jabdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被告".equals(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_jabdje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告").contains(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_jabdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告").contains(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_jabdje());
                    }
                }
            }
        } else if (CaseCategory.CIVIL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (verifyCountAmount(data) || verifySearchTime(startTime, endTime, data.getD_jarq())) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原告", "反诉原告").contains(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_jabdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告", "反诉被告").contains(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_jabdje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告", "原审申请人").contains(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_jabdje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告", "原审被申请人").contains(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_jabdje());
                    }
                }
            }
        } else if (CaseCategory.IMPLEMENT.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (verifyCountAmount(data) || verifySearchTime(startTime, endTime, data.getD_jarq())) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("申请执行人", "申请复议人", "申请人").contains(data.getN_ssdw())) {
                    countAmount(activeMap, data, data.getN_jabdje());
                } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被执行人", "被申请人").contains(data.getN_ssdw())) {
                    countAmount(passiveMap, data, data.getN_jabdje());
                }
            }
        } else if (CaseCategory.CRIMINAL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (verifyCountAmount(data) || verifySearchTime(startTime, endTime, data.getD_jarq())) {
                    continue;
                }
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("自诉人", "反诉人", "附带民事诉讼原告", "附带民事诉讼反诉原告").contains(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_pcpcje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告人", "反诉被告人", "附带民事诉讼被告", "附带民事诉讼反诉被告").contains(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_pcpcje());
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审附带民事诉讼原告", "申请复议人", "原审反诉人").contains(data.getN_ssdw())) {
                        countAmount(activeMap, data, data.getN_pcpcje());
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原审被告人", "原审附带民事诉讼被告", "原审被申请人", "犯罪嫌疑人", "原审反诉被告人").contains(data.getN_ssdw())) {
                        countAmount(passiveMap, data, data.getN_pcpcje());
                    }
                }
            }
        }
    }

    private boolean verifySearchTime(Timestamp startTime, Timestamp endTime, String time) {
        return (!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(TimeUtil.transferTime(time, Regulation.YEAR_MONTH_DAY))
                && TimeUtil.transferTime(time, Regulation.YEAR_MONTH_DAY).before(TimeUtil.getDayBeginTime(startTime)))
                || (!ObjectUtils.isEmpty(endTime) && !ObjectUtils.isEmpty(TimeUtil.transferTime(time, Regulation.YEAR_MONTH_DAY))
                && TimeUtil.transferTime(time, Regulation.YEAR_MONTH_DAY).after(TimeUtil.getDayEndTime(endTime)));
    }

    private boolean verifyCountAmount(CaseDataDTO data) {
        return StringUtils.isBlank(data.getN_ajjzjd())
                || !"已结案".equals(data.getN_ajjzjd())
                || StringUtils.isBlank(data.getD_jarq());
    }

    private void countAmount(Map<String, Double> activeMap, CaseDataDTO data, String amountCode) {
        if (StringUtils.isNotBlank(amountCode)) {
            if (activeMap.containsKey(data.getD_jarq())) {
                Double amount = activeMap.get(data.getD_jarq());
                activeMap.put(data.getD_jarq(), amount + Double.parseDouble(amountCode));
            } else {
                activeMap.put(data.getD_jarq(), Double.parseDouble(amountCode));
            }
        }
    }

    private void judgeLitigationStatus(CaseCategory category, Map<String, Integer> countMap, List<CaseDataDTO> cases) {
        int activeNum = countMap.get("active");
        int passiveNum = countMap.get("passive");
        if (CaseCategory.PRESERVATION.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_slcx()) && "非诉财产保全审查".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "申请人".equals(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被申请人".equals(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                }
            }
        } else if (CaseCategory.ADMINISTRATIVE.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "原告".equals(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被告".equals(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告").contains(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告").contains(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                }
            }
        } else if (CaseCategory.CIVIL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原告", "反诉原告").contains(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告", "反诉被告").contains(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审原告", "原审申请人").contains(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被上诉人", "原审被告", "原审被申请人").contains(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                }
            }
        } else if (CaseCategory.IMPLEMENT.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("申请执行人", "申请复议人", "申请人").contains(data.getN_ssdw())) {
                    activeNum = activeNum + 1;
                } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被执行人", "被申请人").contains(data.getN_ssdw())) {
                    passiveNum = passiveNum + 1;
                }
            }
        } else if (CaseCategory.BANKRUPT.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_slcx()) && Arrays.asList(
                        "破产", "破产清算", "破产重整", "破产和解", "破产申请审查", "强制清算", "强制清算申请审查"
                ).contains(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && "申请人".equals(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && "被申请人".equals(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                }
            }
        } else if (CaseCategory.CRIMINAL.equals(category)) {
            for (CaseDataDTO data : cases) {
                if (StringUtils.isNotBlank(data.getN_slcx()) && "一审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("自诉人", "反诉人", "附带民事诉讼原告", "附带民事诉讼反诉原告").contains(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("被告人", "反诉被告人", "附带民事诉讼被告", "附带民事诉讼反诉被告").contains(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                } else if (StringUtils.isNotBlank(data.getN_slcx()) && "二审".equals(data.getN_slcx())) {
                    if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("上诉人", "原审附带民事诉讼原告", "申请复议人", "原审反诉人").contains(data.getN_ssdw())) {
                        activeNum = activeNum + 1;
                    } else if (StringUtils.isNotBlank(data.getN_ssdw()) && Arrays.asList("原审被告人", "原审附带民事诉讼被告", "原审被申请人", "犯罪嫌疑人", "原审反诉被告人").contains(data.getN_ssdw())) {
                        passiveNum = passiveNum + 1;
                    }
                }
            }
        }
        countMap.put("active", activeNum);
        countMap.put("passive", passiveNum);
    }

    @Override
    public CheckEnterpriseOverviewVO getOverview(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseOverviewVO res = new CheckEnterpriseOverviewVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);
//        String dishonestInfoStr = checkResultService.getJsonData(userId, QueryType.ENT_DISHONEST, searchRecord, entity);
//        String limitHighStr = checkResultService.getJsonData(userId, QueryType.ENT_LIMIT, searchRecord, entity);
        String judicialInvolvementStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        res.setId(queryRecord.getId());
        UserFollowDO follow = userFollowDao.findByEntityIdAndCreatorIdAndDeletedFalse(queryRecord.getEntityId(), userId);
        res.setIsFollow(!ObjectUtils.isEmpty(follow));

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
            EntBasicDTO basic = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBASIC).orElse(new EntBasicDTO());
            res.setEnterpriseName(basic.getENTNAME());
            res.setOldName(basic.getENTNAME_OLD());
            res.setType(basic.getENTTYPE());
            res.setStatus(basic.getENTSTATUS());
            res.setName(basic.getFRNAME());
            res.setEsDate(basic.getESDATE());
            res.setRegCap(basic.getREGCAP());
        }

//        if (StringUtils.isNotBlank(dishonestInfoStr)) {
//            List<ResDishonestDataDTO> data = JSON.parseArray(dishonestInfoStr, ResDishonestDataDTO.class);
//            Integer num = Optional.ofNullable(data.get(0)).map(ResDishonestDataDTO::getSxbzxr_count)
//                    .map(ResDishonestDataDTO.DishonestCount::getCount_current).orElse(0);
//            res.setDishonestNum(num);
//        }
//
//        if (StringUtils.isNotBlank(limitHighStr)) {
//            List<ResLimitDataDTO> data = JSON.parseArray(limitHighStr, ResLimitDataDTO.class);
//            Integer num = Optional.ofNullable(data.get(0)).map(ResLimitDataDTO::getXgbzxr_count)
//                    .map(ResLimitDataDTO.LimitCount::getCount_current).orElse(0);
//            res.setLimitHighNum(num);
//        }

        if (StringUtils.isNotBlank(judicialInvolvementStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialInvolvementStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            Map<String, CaseNumDTO> countMap = judicialResult.getCaseNum();

            res.setCivilCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.CIVIL.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setCriminalCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.CRIMINAL.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setImplementCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.IMPLEMENT.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setAdministrativeCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.ADMINISTRATIVE.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setPreservationCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.PRESERVATION.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setBankruptCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.BANKRUPT.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setJurisdictionCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.JURISDICTION.getCode(), new CaseNumDTO(0, 0, 0))));
            res.setCompensateCase(new CaseBriefDTO(countMap.getOrDefault(CaseCategory.COMPENSATE.getCode(), new CaseNumDTO(0, 0, 0))));

            Integer dishonestNum = Optional.ofNullable(judicialResult.getSx()).map(ResDishonestDataDTO::getSxbzxr_count)
                    .map(ResDishonestDataDTO.DishonestCount::getCount_current).orElse(0);
            res.setDishonestNum(dishonestNum);

            Integer limitNum = Optional.ofNullable(judicialResult.getXg()).map(ResLimitDataDTO::getXgbzxr_count)
                    .map(ResLimitDataDTO.LimitCount::getCount_current).orElse(0);
            res.setLimitHighNum(limitNum);
        }

        return res;
    }

    @Override
    public CheckEnterpriseJudicialVO getDetailByJudicialInfo(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseJudicialVO res = new CheckEnterpriseJudicialVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
//        String dishonestInfoStr = checkResultService.getJsonData(userId, QueryType.ENT_DISHONEST, searchRecord, entity);
//        String limitHighStr = checkResultService.getJsonData(userId, QueryType.ENT_LIMIT, searchRecord, entity);
        String judicialInvolvementStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_JUDICIAL, searchRecord, entity);

        if (StringUtils.isNotBlank(judicialInvolvementStr)) {
            List<ResJudicialDataProdDTO> resJudicialData = JSON.parseArray(judicialInvolvementStr, ResJudicialDataProdDTO.class);
            ResJudicialDataProdDTO judicialResult = resJudicialData.get(0);
            ResJudicialDataDTO.Detail detail = judicialResult.getDetail();

            res.setCivilCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCivil).map(ResJudicialDataDTO.Detail.Civil::getCases).orElse(new ArrayList<>()).size());
            res.setCivilCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCivil).map(ResJudicialDataDTO.Detail.Civil::getCases).orElse(new ArrayList<>()));
            res.setCriminalCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCriminal).map(ResJudicialDataDTO.Detail.Criminal::getCases).orElse(new ArrayList<>()).size());
            res.setCriminalCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCriminal).map(ResJudicialDataDTO.Detail.Criminal::getCases).orElse(new ArrayList<>()));
            res.setAdministrativeCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getAdministrative).map(ResJudicialDataDTO.Detail.Administrative::getCases).orElse(new ArrayList<>()).size());
            res.setAdministrativeCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getAdministrative).map(ResJudicialDataDTO.Detail.Administrative::getCases).orElse(new ArrayList<>()));
            res.setPreservationCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getPreservation).map(ResJudicialDataDTO.Detail.Preservation::getCases).orElse(new ArrayList<>()).size());
            res.setPreservationCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getPreservation).map(ResJudicialDataDTO.Detail.Preservation::getCases).orElse(new ArrayList<>()));
            res.setImplementCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getImplement).map(ResJudicialDataDTO.Detail.Implement::getCases).orElse(new ArrayList<>()).size());
            res.setImplementCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getImplement).map(ResJudicialDataDTO.Detail.Implement::getCases).orElse(new ArrayList<>()));
            res.setBankruptCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getBankrupt).map(ResJudicialDataDTO.Detail.Bankrupt::getCases).orElse(new ArrayList<>()).size());
            res.setBankruptCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getBankrupt).map(ResJudicialDataDTO.Detail.Bankrupt::getCases).orElse(new ArrayList<>()));
            res.setJurisdictionCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getJurisdict).map(ResJudicialDataDTO.Detail.Jurisdict::getCases).orElse(new ArrayList<>()).size());
            res.setJurisdictionCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getJurisdict).map(ResJudicialDataDTO.Detail.Jurisdict::getCases).orElse(new ArrayList<>()));
            res.setCompensateCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCompensate).map(ResJudicialDataDTO.Detail.Compensate::getCases).orElse(new ArrayList<>()).size());
            res.setCompensateCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCompensate).map(ResJudicialDataDTO.Detail.Compensate::getCases).orElse(new ArrayList<>()));

            res.setDishonestInfoCasesNum(Optional.ofNullable(judicialResult.getSx()).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()).size());
            res.setDishonestInfoCases(Optional.ofNullable(judicialResult.getSx()).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()));

            res.setLimitHighCasesNum(Optional.ofNullable(judicialResult.getXg()).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()).size());
            res.setLimitHighCases(Optional.ofNullable(judicialResult.getXg()).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()));
        }

//        if (StringUtils.isNotBlank(dishonestInfoStr)) {
//            List<ResDishonestDataDTO> resultJson = JSON.parseArray(dishonestInfoStr, ResDishonestDataDTO.class);
//            res.setDishonestInfoCasesNum(Optional.ofNullable(resultJson.get(0)).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()).size());
//            res.setDishonestInfoCases(Optional.ofNullable(resultJson.get(0)).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()));
//        }
//
//        if (StringUtils.isNotBlank(limitHighStr)) {
//            List<ResLimitDataDTO> resultJson = JSON.parseArray(limitHighStr, ResLimitDataDTO.class);
//            res.setLimitHighCasesNum(Optional.ofNullable(resultJson.get(0)).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()).size());
//            res.setLimitHighCases(Optional.ofNullable(resultJson.get(0)).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()));
//        }

        return res;
    }


    public static void main(String[] args) {

        String res = FileUtil.getTemplateContent("D:\\workcode\\judicial-data-backend\\files\\深圳大数信科技术有限公司_judicial.txt");

        List<ResJudicialDataProdDTO> resJudicialDataInfos = JSON.parseArray(res, ResJudicialDataProdDTO.class);

        ResJudicialDataProdDTO resJudicialData = resJudicialDataInfos.get(0);

        ResJudicialDataDTO.Detail detail = resJudicialData.getDetail();

        Integer sum = 0;

        ResJudicialDataDTO.Detail.Jurisdict jurisdict = detail.getJurisdict();
        for (CaseJurisdictionDTO aCase : jurisdict.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Preservation preservation = detail.getPreservation();
        for (CasePreservationDTO aCase : preservation.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Administrative administrative = detail.getAdministrative();
        for (CaseAdministrativeDTO aCase : administrative.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Civil civilInfo = detail.getCivil();
        for (CaseCivilDTO aCase : civilInfo.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Implement implementInfo = detail.getImplement();
        for (CaseImplementDTO aCase : implementInfo.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Criminal criminal = detail.getCriminal();
        for (CaseCriminalDTO aCase : criminal.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Bankrupt bankrupt = detail.getBankrupt();
        for (CaseBankruptDTO aCase : bankrupt.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        ResJudicialDataDTO.Detail.Compensate compensate = detail.getCompensate();
        for (CaseCompensateDTO aCase : compensate.getCases()) {
            String cAh = aCase.getC_ah();
            if (StringUtils.isNotBlank(cAh) && cAh.contains("2024")) {
                sum++;
            }
        }

        System.out.println("2024:" + sum);
    }


    @Override
    public CheckEnterpriseJudicialVO getDetailByJudicialInfoNum(Long userId, GetQueryInfoForm form) {
        CheckEnterpriseJudicialVO res = getDetailByJudicialInfo(userId, new GetQueryInfoForm(form.getId()));
        res.setCivilCases(Collections.emptyList());
        res.setCriminalCases(Collections.emptyList());
        res.setAdministrativeCases(Collections.emptyList());
        res.setPreservationCases(Collections.emptyList());
        res.setImplementCases(Collections.emptyList());
        res.setBankruptCases(Collections.emptyList());
        res.setJurisdictionCases(Collections.emptyList());
        res.setCompensateCases(Collections.emptyList());
        res.setDishonestInfoCases(Collections.emptyList());
        res.setLimitHighCases(Collections.emptyList());
        return res;
    }

    @Override
    public PageVO<Object> getDetailByJudicialInfoPage(Long userId, QueryCasePageForm form, Pageable pageable) {
        CheckEnterpriseJudicialVO res = getDetailByJudicialInfo(userId, new GetQueryInfoForm(form.getId()));

        Map<String, List<?>> caseTypeMap = new HashMap<>(16);
        caseTypeMap.put(CaseCategory.CIVIL.getCode(), res.getCivilCases());
        caseTypeMap.put(CaseCategory.CRIMINAL.getCode(), res.getCriminalCases());
        caseTypeMap.put(CaseCategory.ADMINISTRATIVE.getCode(), res.getAdministrativeCases());
        caseTypeMap.put(CaseCategory.PRESERVATION.getCode(), res.getPreservationCases());
        caseTypeMap.put(CaseCategory.IMPLEMENT.getCode(), res.getImplementCases());
        caseTypeMap.put(CaseCategory.BANKRUPT.getCode(), res.getBankruptCases());
        caseTypeMap.put(CaseCategory.JURISDICTION.getCode(), res.getJurisdictionCases());
        caseTypeMap.put(CaseCategory.COMPENSATE.getCode(), res.getCompensateCases());
        caseTypeMap.put("dishonest", res.getDishonestInfoCases());
        caseTypeMap.put("limit", res.getLimitHighCases());

        String caseType = form.getType();
        List<?> cases = caseTypeMap.get(caseType);

        if (CollectionUtils.isEmpty(cases)) {
            return new PageVO<>(0L, Collections.emptyList());
        }

        if (ObjectUtils.isEmpty(form.getCaseState()) || CaseState.ALL.equals(form.getCaseState())) {
            if ("dishonest".equals(caseType) || "limit".equals(caseType)) {
                return new PageVO<>((long) cases.size(), new ArrayList<>(PageUtil.getPage(cases, pageable)));
            }

            List<CaseDataDTO> resCases = cases.stream().map(m -> {
                CaseDataDTO data = new CaseDataDTO();
                BeanUtils.copyProperties(m, data);
                return data;
            }).sorted(
                    Comparator.comparing(CaseDataDTO::getD_larq, Comparator.nullsFirst(String::compareTo)).reversed()
            ).collect(Collectors.toList());
            return new PageVO<>((long) cases.size(), new ArrayList<>(PageUtil.getPage(resCases, pageable)));
        } else if (CaseState.CLOSE.equals(form.getCaseState()) || CaseState.NOT_CLOSE.equals(form.getCaseState())) {
            List<CaseDataDTO> resCases = cases.stream().map(m -> {
                CaseDataDTO data = new CaseDataDTO();
                BeanUtils.copyProperties(m, data);
                return data;
            }).filter(data -> form.getCaseState().getValue().equals(data.getN_ajjzjd())).sorted(
                    Comparator.comparing(CaseDataDTO::getD_larq, Comparator.nullsFirst(String::compareTo)).reversed()
            ).collect(Collectors.toList());
            return new PageVO<>((long) resCases.size(), new ArrayList<>(PageUtil.getPage(resCases, pageable)));
        }

        return new PageVO<>(0L, Collections.emptyList());
    }

    @Override
    public CheckEnterpriseBusinessRiskVO getDetailByBusinessRisk(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseBusinessRiskVO res = new CheckEnterpriseBusinessRiskVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
            res.setBreakLawList(Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBREAKLAW).orElse(new ArrayList<>())
                    .stream().map(EntBreakLawVO::getEntBreakLaw).collect(Collectors.toList()));
        }

        return res;
    }

    @Override
    public CheckEnterpriseBusinessInfoVO getDetailByBusinessInfo(Long userId, GetQueryInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseBusinessInfoVO res = new CheckEnterpriseBusinessInfoVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);
            EntBasicDTO basic = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getBASIC).orElse(new EntBasicDTO());
            res.setBasicInfo(EntBasicVO.getEntBasic(basic));

            List<EntPersonVO> person = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getPERSON).orElse(new ArrayList<>())
                    .stream().map(EntPersonVO::getEntPerson).collect(Collectors.toList());
            res.setPerson(person);
            res.setPersonNum(person.size());

            List<EntFiliationVO> filiation = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getFILIATION).orElse(new ArrayList<>())
                    .stream().map(EntFiliationVO::getEntFiliation).collect(Collectors.toList());
            res.setFiliation(filiation);
            res.setFiliationNum(filiation.size());

            List<EntShareholderVO> shareholder = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getSHAREHOLDER).orElse(new ArrayList<>())
                    .stream().map(EntShareholderVO::getEntShareholder).collect(Collectors.toList());
            res.setShareholder(shareholder);
            res.setShareholderNum(shareholder.size());

            List<EntInvVO> entinv = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getENTINV).orElse(new ArrayList<>())
                    .stream().map(EntInvVO::getEntEntinv).collect(Collectors.toList());
            res.setEntinv(entinv);
            res.setEntinvNum(entinv.size());
            res.setEntinvAmount(entinv.stream().filter(data -> StringUtils.isNotBlank(data.getSubconam())).mapToDouble(data -> Double.parseDouble(data.getSubconam())).sum());

            List<EntAlterVO> alter = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getALTER).orElse(new ArrayList<>())
                    .stream().map(EntAlterVO::getEntAlter).collect(Collectors.toList());
            res.setAlter(alter);
            res.setAlterNum(alter.size());

            List<EntYearReportBasicDTO> entYearReports = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTBASIC).orElse(new ArrayList<>());
            if (!CollectionUtils.isEmpty(entYearReports)) {
                res.getBasicInfo().setTel(entYearReports.get(0).getTEL());
            }
            List<EntReportSimpleVO> report = entYearReports.stream().map(EntReportSimpleVO::getEntReportSimple).collect(Collectors.toList());
            res.setReport(report);
            res.setReportNum(report.size());
        }

        return res;
    }

    @Override
    public CheckEnterpriseYearReportVO getDetailByReport(Long userId, GetReportInfoForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_AUTHORIZATION_NOT_PASS);

        CheckEnterpriseYearReportVO res = new CheckEnterpriseYearReportVO();
        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(userId, queryRecord, searchRecord);
        String companyInfoStr = checkResultService.getJsonDataProd(userId, QueryType.ENT_BASIC, searchRecord, entity);

        if (StringUtils.isNotBlank(companyInfoStr)) {
            ResEntDetailDTO totalInfo = JSON.parseObject(companyInfoStr, ResEntDetailDTO.class);

            Map<String, EntYearReportBasicDTO> basicMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTBASIC).orElse(new ArrayList<>())
                    .stream().collect(Collectors.toMap(EntYearReportBasicDTO::getANCHEID, v -> v));
            res.setBasic(EntReportBasicVO.getReportBasic(basicMap.getOrDefault(form.getReportId(), new EntYearReportBasicDTO())));

            Map<String, List<EntYearReportWebsiteDTO>> websiteMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTWEBSITEINFO).orElse(new ArrayList<>())
                    .stream().collect(Collectors.groupingBy(EntYearReportWebsiteDTO::getANCHEID));
            res.setWebsite(websiteMap.getOrDefault(form.getReportId(), new ArrayList<>()).stream().map(EntReportWebsiteVO::getReportWebsite).collect(Collectors.toList()));

            Map<String, List<EntYearReportPaidupCapitalDTO>> paidupCapitalMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTPAIDUPCAPITAL).orElse(new ArrayList<>())
                    .stream().collect(Collectors.groupingBy(EntYearReportPaidupCapitalDTO::getANCHEID));
            Map<String, List<EntYearReportSubCapitalDTO>> subCapitalMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTSUBCAPITAL).orElse(new ArrayList<>())
                    .stream().collect(Collectors.groupingBy(EntYearReportSubCapitalDTO::getANCHEID));
            Map<String, EntYearReportSubCapitalDTO> subCapital = subCapitalMap.getOrDefault(form.getReportId(), new ArrayList<>()).stream()
                    .collect(Collectors.toMap(EntYearReportSubCapitalDTO::getINV, v -> v, (v1, v2) -> v1));
            res.setCapital(paidupCapitalMap.getOrDefault(form.getReportId(), new ArrayList<>()).stream().map(data -> {
                EntReportCapitalVO capital = new EntReportCapitalVO();
                capital.setAncheid(data.getANCHEID());
                capital.setCondate(data.getCONDATE());
                capital.setConform(data.getCONFORM());
                capital.setLiacconam(data.getLIACCONAM());
                capital.setLisubconam(subCapital.getOrDefault(data.getINV(), new EntYearReportSubCapitalDTO()).getLISUBCONAM());
                capital.setInv(data.getINV());
                return capital;
            }).collect(Collectors.toList()));

            Map<String, List<EntYearReportGuaranteeDTO>> guaranteeMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTFORGUARANTEE).orElse(new ArrayList<>())
                    .stream().collect(Collectors.groupingBy(EntYearReportGuaranteeDTO::getANCHEID));
            res.setGuarantee(guaranteeMap.getOrDefault(form.getReportId(), new ArrayList<>()).stream().map(EntReportGuaranteeVO::getReportGuarantee).collect(Collectors.toList()));

            Map<String, EntYearReportSocsecDTO> socsecMap = Optional.ofNullable(totalInfo).map(ResEntDetailDTO::getYEARREPORTSOCSEC).orElse(new ArrayList<>())
                    .stream().collect(Collectors.toMap(EntYearReportSocsecDTO::getANCHEID, v -> v));
            res.setSocsec(EntReportSocsecVO.getReportSocsec(socsecMap.getOrDefault(form.getReportId(), new EntYearReportSocsecDTO())));
        }

        return res;
    }

}
